import { ProTable } from '@ant-design/pro-components';
import {
  Button,
  Tag,
  Popconfirm,
  message,
  Breadcrumb,
  Select,
  Space,
} from 'antd';
import { PageContainer } from '@ant-design/pro-layout';
import { useRequest } from 'umi';
import { PlusOutlined } from '@ant-design/icons';
import type { ProFormInstance } from '@ant-design/pro-components';

import {
  ModalForm,
  ProForm,
  ProFormDateRangePicker,
  ProFormSelect,
  ProFormText,
  ProFormDependency,
  ProFormDatePicker,
} from '@ant-design/pro-components';
import { useRef } from 'react';

import SearchByRole from '@/components/SearchByRole';

const waitTime = (time: number = 100) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(true);
    }, time);
  });
};

export default () => {
  const { Option } = Select;
  const formRef = useRef<ProFormInstance>();

  //获取所有方向
  const findAllDirection = useRequest((data = null) => {
    return {
      url: 'http://10.1.40.84:9993/direction/findAllDirection',
      method: 'POST',
      headers: {
        Authorization: localStorage.getItem('token') || '',
      },
      data,
    };
  });

  //获取研究生名单
  const findAllPostgraduateByMutilPart = useRequest((data = {}) => {
    return {
      url: 'http://10.1.40.84:9993/post/findAllPostgraduateByMutilPart',
      method: 'POST',
      headers: {
        Authorization: localStorage.getItem('token') || '',
      },
      data,
    };
  });
  //添加研究生
  const addPostgraduate = useRequest(
    (data = {}) => {
      return {
        url: 'http://10.1.40.84:9993/post/addPostgraduate',
        method: 'POST',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
        data,
      };
    },
    {
      manual: true,
    },
  );

  //删除研究生
  const delPostgraduate = useRequest(
    (data = {}) => {
      return {
        url: 'http://10.1.40.84:9993/post/delPostgraduate',
        method: 'POST',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
        data,
      };
    },
    {
      manual: true,
    },
  );

  //更新研究生
  const updatePostgraduate = useRequest(
    (data = {}) => {
      return {
        url: 'http://10.1.40.84:9993/post/updatePostgraduate',
        method: 'POST',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
        data,
      };
    },
    {
      manual: true,
    },
  );

  const columns = [
    {
      title: '年度',
      align: 'center',
      dataIndex: 'years',
      key: 'years',
      valueType: 'dateYear',
      hideInTable: true,
    },
    {
      title: '年度',
      align: 'center',
      dataIndex: 'years',
      key: 'years',
      // valueType: 'dateYear',
      hideInSearch: true,
    },
    {
      title: '序号',
      align: 'center',
      dataIndex: 'seq',
      key: 'seq',
      hideInSearch: true,
    },
    {
      title: '学号',
      align: 'center',
      dataIndex: 'stuId',
      key: 'stuId',
    },
    {
      title: '姓名',
      align: 'center',
      dataIndex: 'stuName',
      key: 'stuName',
    },
    {
      title: '培养类别',
      align: 'center',
      dataIndex: 'trainType',
      key: 'trainType',
      valueType: 'select',
      valueEnum: {
        博士点: '博士点',
        硕士点: '硕士点',
      },
    },
    {
      title: '学位点代码',
      align: 'center',
      dataIndex: 'trainId',
      key: 'trainId',
      hideInSearch: true,
    },
    {
      title: '学位点名称',
      align: 'center',
      dataIndex: 'trainName',
      key: 'trainName',
      valueType: 'select',
      valueEnum: {
        电气工程: '电气工程',
        机械工程: '机械工程',
      },
    },
    {
      title: '专业',
      align: 'center',
      dataIndex: 'major',
      key: 'major',
      hideInSearch: true,
    },
    {
      title: '导师',
      align: 'center',
      dataIndex: 'directerId',
      key: 'directerId',
      hideInTable: true,
      renderFormItem: () => {
        return (
          <Select
            showSearch
            filterOption={(input, option) =>
              (option!.children as unknown as string)
                .toLowerCase()
                .includes(input.toLowerCase())
            }
          >
            {SearchByRole('管理员视角')?.people?.map((item: any) => (
              <Option key={item.value} value={item.value}>
                {item.label}
              </Option>
            ))}
          </Select>
        );
      },
    },
    {
      title: '导师',
      align: 'center',
      dataIndex: 'directerName',
      key: 'directerName',
      hideInSearch: true,
    },
    {
      title: '状态',
      align: 'center',
      dataIndex: 'trainStatus',
      key: 'trainStatus',
      valueType: 'select',
      valueEnum: {
        在读: '在读',
        毕业: '毕业',
      },
    },
    {
      title: '研究方向',
      align: 'center',
      dataIndex: 'direction',
      key: 'direction',
      renderFormItem: () => {
        return (
          <Select
            showSearch
            filterOption={(input, option) =>
              (option!.children as unknown as string)
                .toLowerCase()
                .includes(input.toLowerCase())
            }
          >
            {findAllDirection?.data?.map((item: any) => (
              <Option key={item.id} value={item.directionName}>
                {item.directionName}
              </Option>
            ))}
          </Select>
        );
      },
    },
    {
      title: '操作',
      key: 'action',
      align: 'center',
      hideInSearch: true,
      render: (_: any, record: any) => {
        // console.log(record);
        return (
          <Space>
            <ModalForm
              title="编辑信息"
              formRef={formRef}
              trigger={<a>编辑</a>}
              initialValues={{ ...record, years: record.years + '' }}
              autoFocusFirstInput
              modalProps={{
                destroyOnClose: true,
              }}
              submitTimeout={2000}
              onFinish={async (values) => {
                console.log(values);
                await waitTime(2000);
                updatePostgraduate.run(values).then(() => {
                  findAllPostgraduateByMutilPart.run().then(() => {
                    message.success('更新成功！');
                  });
                });
                return true;
              }}
              grid
            >
              <ProForm.Group>
                <ProFormText name="id" hidden />
                <ProFormDatePicker.Year
                  name="years"
                  label="年度"
                  colProps={{ span: 4 }}
                  rules={[{ required: true }]}
                />
                <ProFormText
                  name="seq"
                  label="序号"
                  colProps={{ span: 4 }}
                  rules={[{ required: true }]}
                />
                <ProFormText
                  name="stuId"
                  label="学号"
                  colProps={{ span: 6 }}
                  rules={[{ required: true }]}
                />
                <ProFormText
                  name="stuName"
                  label="姓名"
                  colProps={{ span: 6 }}
                  rules={[{ required: true }]}
                />
                <ProFormSelect
                  colProps={{ span: 4 }}
                  options={[
                    {
                      value: '博士点',
                      label: '博士点',
                    },
                    {
                      value: '硕士点',
                      label: '硕士点',
                    },
                  ]}
                  name="trainType"
                  label="培养类别"
                  rules={[{ required: true }]}
                />
                <ProFormSelect
                  colProps={{ span: 4 }}
                  options={[
                    {
                      value: '电气工程',
                      label: '电气工程',
                    },
                    {
                      value: '机械工程',
                      label: '机械工程',
                    },
                  ]}
                  name="trainName"
                  label="学位点名称"
                  rules={[{ required: true }]}
                  fieldProps={{
                    onChange: (value: any) => {
                      formRef.current?.setFieldsValue({
                        trainId: value === '电气工程' ? '0808' : '0802',
                      });
                    },
                  }}
                />
                <ProFormText
                  name="trainId"
                  label={`学位点代码`}
                  disabled
                  colProps={{ span: 4 }}
                  rules={[{ required: true }]}
                />
                <ProFormText
                  name="major"
                  label={`专业`}
                  colProps={{ span: 6 }}
                  rules={[{ required: true }]}
                />

                <ProFormSelect
                  colProps={{ span: 6 }}
                  name="directerId"
                  label="导师"
                  rules={[{ required: true }]}
                  fieldProps={{
                    onChange: (value: any, option: any) => {
                      formRef.current?.setFieldsValue({
                        directerName: option.label,
                      });
                    },
                    options: SearchByRole('管理员视角')?.people || [],
                    showSearch: true,
                  }}
                />

                <ProFormText name="directerName" hidden />
                <ProFormSelect
                  colProps={{ span: 4 }}
                  options={[
                    {
                      value: '在读',
                      label: '在读',
                    },
                    {
                      value: '毕业',
                      label: '毕业',
                    },
                  ]}
                  name="trainStatus"
                  label="状态"
                  rules={[{ required: true }]}
                />
              </ProForm.Group>
            </ModalForm>
            <Popconfirm
              title="确定删除该学生吗？"
              onConfirm={() => {
                delPostgraduate
                  .run({
                    id: record.id,
                  })
                  .then(() => {
                    findAllPostgraduateByMutilPart.run().then(() => {
                      message.info('删除成功');
                    });
                  });
              }}
              onCancel={() => {}}
              okText="确认"
              cancelText="取消"
            >
              <a href="#">删除</a>
            </Popconfirm>
          </Space>
        );
      },
    },
  ];
  return (
    <PageContainer
      header={{
        title: ' ',
        breadcrumb: (
          <Breadcrumb>
            <Breadcrumb.Item>队伍建设与人才培养</Breadcrumb.Item>
            <Breadcrumb.Item>研究生培养</Breadcrumb.Item>
          </Breadcrumb>
        ),
      }}
      // extra={[
      //   <Button
      //     key="1"
      //     type="primary"
      //     onClick={() => {
      //       console.log(SearchByRole('管理员视角')?.people);
      //     }}
      //   >
      //     主操作
      //   </Button>,
      // ]}
    >
      <ProTable
        columns={columns}
        dataSource={findAllPostgraduateByMutilPart?.data || []}
        rowKey="id"
        pagination={{
          showQuickJumper: true,
        }}
        toolBarRender={() => [
          <ModalForm
            title="新增研究生"
            formRef={formRef}
            trigger={
              <Button key="button" icon={<PlusOutlined />} type="primary">
                新增研究生
              </Button>
            }
            autoFocusFirstInput
            modalProps={{
              onCancel: () => console.log('run'),
              destroyOnClose: true,
            }}
            submitTimeout={2000}
            onFinish={async (values) => {
              await waitTime(2000);
              addPostgraduate.run(values).then(() => {
                findAllPostgraduateByMutilPart.run();
                message.success('提交成功');
              });
              return true;
            }}
            grid
          >
            <ProForm.Group>
              {/* <ProFormText
                name="years"
                label="年度"
                colProps={{ span: 4 }}
                rules={[{ required: true }]}
              /> */}
              <ProFormDatePicker.Year
                name="years"
                label="年度"
                colProps={{ span: 4 }}
                rules={[{ required: true }]}
              />
              <ProFormText
                name="seq"
                label="序号"
                colProps={{ span: 4 }}
                rules={[{ required: true }]}
              />
              <ProFormText
                name="stuId"
                label="学号"
                colProps={{ span: 6 }}
                rules={[{ required: true }]}
              />
              <ProFormText
                name="stuName"
                label="姓名"
                colProps={{ span: 6 }}
                rules={[{ required: true }]}
              />
              <ProFormSelect
                colProps={{ span: 4 }}
                options={[
                  {
                    value: '博士点',
                    label: '博士点',
                  },
                  {
                    value: '硕士点',
                    label: '硕士点',
                  },
                ]}
                name="trainType"
                label="培养类别"
                rules={[{ required: true }]}
              />
              <ProFormSelect
                colProps={{ span: 4 }}
                options={[
                  {
                    value: '电气工程',
                    label: '电气工程',
                  },
                  {
                    value: '机械工程',
                    label: '机械工程',
                  },
                ]}
                name="trainName"
                label="学位点名称"
                rules={[{ required: true }]}
                fieldProps={{
                  onChange: (value: any) => {
                    formRef.current?.setFieldsValue({
                      trainId: value === '电气工程' ? '0808' : '0802',
                    });
                  },
                }}
              />
              <ProFormText
                name="trainId"
                label={`学位点代码`}
                disabled
                colProps={{ span: 4 }}
                rules={[{ required: true }]}
              />
              <ProFormText
                name="major"
                label={`专业`}
                colProps={{ span: 6 }}
                rules={[{ required: true }]}
              />

              <ProFormSelect
                colProps={{ span: 6 }}
                name="directerId"
                label="导师"
                rules={[{ required: true }]}
                fieldProps={{
                  onChange: (value: any, option: any) => {
                    formRef.current?.setFieldsValue({
                      directerName: option.label,
                    });
                  },
                  options: SearchByRole('管理员视角')?.people || [],
                  showSearch: true,
                }}
              />

              <ProFormText name="directerName" hidden />
              <ProFormSelect
                colProps={{ span: 4 }}
                options={[
                  {
                    value: '在读',
                    label: '在读',
                  },
                  {
                    value: '毕业',
                    label: '毕业',
                  },
                ]}
                name="trainStatus"
                label="状态"
                rules={[{ required: true }]}
              />
            </ProForm.Group>
          </ModalForm>,
        ]}
        loading={findAllPostgraduateByMutilPart.loading}
        dateFormatter="string"
        headerTitle="研究生列表"
        options={false}
        onReset={() => {
          findAllPostgraduateByMutilPart.run();
        }}
        onSubmit={(e) => {
          console.log(e);
          if (Object.keys(e).length !== 0) {
            findAllPostgraduateByMutilPart.run(e);
          }
        }}
      />
    </PageContainer>
  );
};
